"""
API 路由定义
"""

import asyncio
import logging
import time
from pathlib import Path
from typing import Optional
import aiofiles

from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Response
from fastapi.responses import JSONResponse, PlainTextResponse

from ..models.models import (
    TaskResponse, ProcessingResult, ErrorResponse, HealthResponse, DetailedHealthResponse,
    StatsResponse, TaskStatus, ProcessingMode
)
from ..services import dialogue_service, FileService, health_service
from ..core.config import settings

logger = logging.getLogger(__name__)

router = APIRouter()

@router.post("/upload", response_model=TaskResponse)
async def upload_audio(
    background_tasks: BackgroundTasks,
    file: UploadFile = File(...),
    processing_mode: ProcessingMode = Form(ProcessingMode.AUTO),
    chunk_size: Optional[int] = Form(900),
    timeout: Optional[int] = Form(3600)
):
    """
    上传音频文件并开始处理
    
    - **file**: 音频文件 (支持 .wav, .mp3, .m4a, .flac, .aac)
    - **processing_mode**: 处理模式 (auto/interactive/rules)
    - **chunk_size**: 大文件分割大小（秒，默认900）
    - **timeout**: 处理超时时间（秒，默认3600）
    """
    try:
        # 保存上传的文件
        file_path = await FileService.save_upload_file(file)
        
        # 创建处理任务
        task_id = await dialogue_service.create_task(
            file_path=file_path,
            original_filename=file.filename,
            processing_mode=processing_mode,
            chunk_size=chunk_size,
            timeout=timeout
        )
        
        # 添加后台任务进行处理
        background_tasks.add_task(process_audio_task, task_id, file_path)
        
        return TaskResponse(
            task_id=task_id,
            status=TaskStatus.PENDING,
            message="任务已创建，正在处理中...",
            created_at=dialogue_service.tasks[task_id]["created_at"]
        )
        
    except Exception as e:
        logger.error(f"上传文件失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"上传失败: {str(e)}")

async def process_audio_task(task_id: str, file_path: Path):
    """后台处理音频任务"""
    try:
        await dialogue_service.process_task(task_id)
    except Exception as e:
        logger.error(f"后台任务处理失败 {task_id}: {str(e)}")
    finally:
        # 清理上传文件
        FileService.cleanup_upload_file(file_path)

@router.get("/task/{task_id}/status", response_model=TaskResponse)
async def get_task_status(task_id: str, include_details: bool = False):
    """
    获取任务状态
    
    - **task_id**: 任务ID
    - **include_details**: 是否包含详细结果（仅完成状态时有效）
    """
    try:
        status_data = await dialogue_service.get_task_status(task_id, include_details)
        
        return TaskResponse(
            task_id=status_data["task_id"],
            status=status_data["status"],
            message=status_data.get("message", ""),
            created_at=status_data["created_at"],
            updated_at=status_data.get("updated_at"),
            progress=status_data.get("progress", 0.0)
        )
        
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        logger.error(f"获取任务状态失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取状态失败: {str(e)}")

@router.get("/task/{task_id}/result", response_model=ProcessingResult)
async def get_task_result(task_id: str):
    """
    获取任务处理结果
    
    - **task_id**: 任务ID
    """
    try:
        result = await dialogue_service.get_task_result(task_id)
        return ProcessingResult(**result)
        
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        logger.error(f"获取任务结果失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取结果失败: {str(e)}")

@router.get("/task/{task_id}/files/{file_type}")
async def get_task_file(task_id: str, file_type: str):
    """
    获取任务生成的文件内容
    
    - **task_id**: 任务ID
    - **file_type**: 文件类型 (transcript/analysis/prd/meeting_notes/checklist/traceability_matrix/project_plan/test_cases/implementation_guide)
    """
    try:
        content, mime_type = await dialogue_service.get_file_content(task_id, file_type)
        
        # 根据文件类型返回合适的响应
        if mime_type == "application/json":
            return JSONResponse(content=content)
        else:
            return PlainTextResponse(content=content, media_type=mime_type)
            
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        logger.error(f"获取文件内容失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取文件失败: {str(e)}")

@router.get("/health", response_model=HealthResponse)
async def health_check():
    """
    基础健康检查
    
    返回服务的基本健康状态信息
    """
    try:
        health_data = health_service.get_basic_health()
        return HealthResponse(**health_data)
    except Exception as e:
        logger.error(f"健康检查失败: {str(e)}")
        return HealthResponse(
            status="error",
            service="dialogue_service",
            version="1.0.0",
            timestamp=time.time()
        )

@router.get("/health/detailed", response_model=DetailedHealthResponse)
async def detailed_health_check():
    """
    详细健康检查
    
    返回包含系统资源、模型状态、存储信息等的详细健康报告
    """
    try:
        health_data = health_service.get_detailed_health()
        return DetailedHealthResponse(**health_data)
    except Exception as e:
        logger.error(f"详细健康检查失败: {str(e)}")
        return DetailedHealthResponse(
            status="error",
            service="dialogue_service", 
            version="1.0.0",
            timestamp=time.time(),
            uptime=0.0,
            overall_status="error"
        )

@router.get("/stats", response_model=StatsResponse)
async def get_stats():
    """获取服务统计信息"""
    stats = dialogue_service.get_stats()
    
    return StatsResponse(
        total_tasks=stats["total_tasks"],
        completed_tasks=stats["completed_tasks"],
        failed_tasks=stats["failed_tasks"],
        active_tasks=stats["active_tasks"],
        average_processing_time=stats.get("average_processing_time"),
        total_audio_duration=stats.get("total_audio_duration")
    )

@router.post("/admin/cleanup")
async def cleanup_old_tasks(days: int = 7):
    """
    清理旧任务（管理员接口）
    
    - **days**: 清理多少天前的任务，默认7天
    """
    try:
        dialogue_service.cleanup_old_tasks(days)
        return {"message": f"清理了{days}天前的旧任务"}
    except Exception as e:
        logger.error(f"清理任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"清理失败: {str(e)}")

@router.get("/task/{task_id}/logs")
async def get_task_logs(task_id: str):
    """
    获取任务处理日志
    
    - **task_id**: 任务ID
    """
    try:
        # 读取日志文件
        log_file = settings.LOGS_DIR / f"task_{task_id}.log"
        if not log_file.exists():
            raise HTTPException(status_code=404, detail="任务日志不存在")
        
        async with aiofiles.open(log_file, 'r', encoding='utf-8') as f:
            logs = await f.read()
        
        return PlainTextResponse(content=logs, media_type="text/plain")
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取任务日志失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取日志失败: {str(e)}")

# 注意：异常处理器应该在FastAPI应用实例上定义，而不是在APIRouter上